package com.group3.service.impl;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.group3.dao.TeacherMapper;
import com.group3.domain.Teacher;
import com.group3.domain.TeacherExample;
import com.group3.exception.BusinessException;
import com.group3.exception.ExceptionEnum;
import com.group3.pojo.UpdatePassword;
import com.group3.service.TeacherService;
import com.group3.utils.JWTUtils;
import com.group3.utils.Md5;
import com.group3.utils.Result;
import com.group3.utils.ResultUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * TeacherServiceImpl
 *
 * @author HY
 * 2021/06/10 16:52
 **/


@Service
public class TeacherServiceImpl implements TeacherService {
    @Resource
    private TeacherMapper teacherMapper;

    @Override
    public Result putPassword(UpdatePassword updatePassword, String token) {
        updatePassword.setPassword(Md5.encodeByMD5(updatePassword.getPassword()));//为获取到的密码加密
        updatePassword.setNewPassword(Md5.encodeByMD5(updatePassword.getNewPassword()));

        DecodedJWT jwt = JWTUtils.getToken(token);//获取token
        String teacherId = jwt.getClaim("id").asString();//获取登录老师的id

        Teacher teacher = new Teacher();
        teacher.setTeacherId(teacherId);
        teacher.setPassword(updatePassword.getNewPassword());

        TeacherExample teacherExample = new TeacherExample();
        teacherExample
                .createCriteria()
                .andTeacherIdEqualTo(teacherId)
                .andPasswordEqualTo(updatePassword.getPassword());//添加查询条件

        if (teacherMapper.selectByExample(teacherExample).isEmpty()) {//查询结果为空即原密码错误
            throw new BusinessException(ExceptionEnum.OLD_PASSWORD_ERR);//抛出原密码错误异常
        }else {
            int result = teacherMapper.updateByPrimaryKeySelective(teacher);//更新密码操作结果
            if (result > 0) {
                return ResultUtil.success();//返回成功信息
            } else{
                throw new BusinessException(ExceptionEnum.ERROR);
            }
        }
    }
}
